<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Account;

use AuctionCore\Common\PhpRedis;

/**
 * 唯一登录处理类
 * @author Administrator
 */
class UniqLogin
{

    //private $crypt_key = 'erp_unique_login_';
    private $crypt_key = '100009';


    /**
     * 设置token
     * @param integer $uid 登录用户id或用户名
     * @param string $expire 登录有效期
     * @return string $token 检查唯一登录的key
     */
    public function update($uid, $expire = '')
    {
        $redis = new PhpRedis(0);
        $now = time();
        if (!$expire) {
            $expire = (86400 - ($now % 86400));
        }
        $unique_login_token = $this->generateAccessToken($uid);
        $arr = [
            'uid'=>$uid,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY',$this->crypt_key,$arr);
       // $redis->set($this->crypt_key.$uid, $unique_login_token, $expire);
        $redis->set($keyName, $unique_login_token, $expire);
        return $unique_login_token;
    }

    /**
     * 生成唯一登录token
     * @param $uid
     * @return string
     */
    private function generateAccessToken($uid)
    {
        $auth = C('auth');
        $date = date('Y-m-d H:i:s');
        $token_md5 = md5(md5($date.$auth['token']));
        $token = think_encrypt($date.'O_O'.$token_md5,$auth['key'].$uid);
        return $token;
    }

    /**
     * 唯一登录检查
     * @param $uid
     * @param $unique_login_token
     * @return bool
     */
    public function check($uid, $unique_login_token)
    {
        if (!$uid || !$unique_login_token)
            return false;
        $redis = new PhpRedis(0);
        $arr = [
            'uid'=>$uid,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY',$this->crypt_key,$arr);
        $redis_unique_login_token = $redis->get($keyName);
        //$redis_unique_login_token = $redis->get($this->crypt_key.$uid);
        return $redis_unique_login_token == $unique_login_token;
    }

}

//end class